package com.dina.saas.peccancy.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.dina.saas.peccancy.domain.Params;
import com.dina.saas.peccancy.domain.ResponsePeccMsg;

public class ShenZhenTask extends Task {
	private Parser parser = new ShenZhenParser();
	private ImagePreProcess imagePreProcess = new SZImagePreProcess();
	private Logger logger = Logger.getLogger(ShenZhenTask.class);

	@Override
	public ResponsePeccMsg execute() {
		ResponsePeccMsg peccMsg = new ResponsePeccMsg("listPecc", 1, "");
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpHost proxy = new HttpHost("127.0.0.1", 8888);//测试时fiddler监视使用   
		httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
				proxy);
		httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
			public boolean isRedirected(HttpRequest request,
					HttpResponse response, HttpContext context) {
				boolean isRedirect = false;
				try {
					isRedirect = super.isRedirected(request, response, context);
				} catch (ProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!isRedirect) {
					int responseCode = response.getStatusLine().getStatusCode();
					if (responseCode == 301 || responseCode == 302) {
						return true;
					}
				}
				return false;
			}
		});

		CookieStore cookieStore = new BasicCookieStore();
		HttpContext httpContext = new BasicHttpContext();
		httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		httpclient.getParams().setIntParameter("http.socket.timeout", 5000);
		HttpPost httppost = new HttpPost(this.getEncodingUrl());
		HttpGet httpGet = new HttpGet(this.getEncodingPicUrl() + "?rnd="
				+ Math.random());
		httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		try {
			HttpResponse httpResponse = httpclient
					.execute(httpGet, httpContext);
			int httpCode = httpResponse.getStatusLine().getStatusCode();
			if (httpCode == 200) {
				HttpEntity ent = httpResponse.getEntity();
				InputStream inputStream = ent.getContent();
				String picResult = imagePreProcess.getAllOcr(inputStream);
				if (ent != null)
					ent.consumeContent();
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				Params requestParams = requestMsg.getParams();
				if (params != null) {
					params.add(new BasicNameValuePair("stc", "69404"));
					params.add(new BasicNameValuePair("stype", "0"));
					params.add(new BasicNameValuePair("cl", requestParams
							.getVehicleType()));
					params.add(new BasicNameValuePair("image_code", picResult));
					params.add(new BasicNameValuePair("fdjh", requestParams
							.getEngineNo()));
					params.add(new BasicNameValuePair("cph", requestParams
							.getBrandId()));
				}
				httppost.addHeader("Content-Type",
						"application/x-www-form-urlencoded");
				httppost.addHeader("Accept-Language", "zh-cn");
				httppost.addHeader("Accept-Encoding", "gzip, deflate");
				httppost.addHeader("Referer",
						"http://www.stc.gov.cn/search/vehicle_peccacy.asp");
				httppost.addHeader("Origin", "http://www.stc.gov.cn");
				httppost.setEntity(new UrlEncodedFormEntity(params, "gb2312"));
				HttpResponse response = httpclient.execute(httppost,
						httpContext);
				if (response.getStatusLine().getStatusCode() == 200) {// 如果状态码为200,就是正常返回
					ent = httpResponse.getEntity();
					this.result = EntityUtils.toString(response.getEntity(),"gb2312");
					peccMsg = parser.parseAll(result);
				//	System.out.println(result);
				} else {
					logger.error("URL[ " + url + " ]httpCode return is  "
							+ response.getStatusLine().getStatusCode()
							+ " not OK,pls check the url!");
					peccMsg.setResultNote(Constants.HTTP_ERROR);
					return peccMsg;
				}
			} else {
				logger.error("URL[ " + this.getEncodingPicUrl()
						+ " ]httpCode return is  " + httpCode
						+ " not OK,pls check the url!");
				peccMsg.setResultNote(Constants.HTTP_ERROR);
				return peccMsg;
			}
			
			Params requestParams = requestMsg.getParams();
			peccMsg.setPageNo(requestParams.getPageNo());
			Integer totalRecord = peccMsg.getTotalRecordNum();
			if(totalRecord==0){
				peccMsg.setResultNote(Constants.NO_RESULT_ERROR);
				return peccMsg;
			}
			Integer start = requestParams.getPagesize()
					* requestParams.getPageNo();
			Integer end = (start + requestParams.getPagesize()) > totalRecord ? totalRecord
					: (start + requestParams.getPagesize());
			if (start >= end) {
				peccMsg.setResultNote(Constants.PARAM_ERROR);
				peccMsg.getDetail().setPeccancyArray(null);
				peccMsg.setPages(0);
				peccMsg.setTotalRecordNum(0);
				return peccMsg;
			}
			List<Object> data = peccMsg.getDetail().getPeccancyArray()
					.subList(start, end);
			int p = (totalRecord % requestParams.getPagesize()) == 0 ? 0 : 1;
			peccMsg.setPages(totalRecord / requestParams.getPagesize() + p);
			peccMsg.getDetail().setPeccancyArray(data);
		} catch (ClientProtocolException e) {
			peccMsg.setResultNote(Constants.HTTP_ERROR);
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			logger.error(e);
			peccMsg.setResultNote(Constants.HTTP_ERROR);
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (httpclient != null) {
				httpclient.getConnectionManager().shutdown();
				httpclient = null;
			}
		}
		// TODO Auto-generated method stub
		return peccMsg;
	}

}
